package com.javafamily.service.Impl;

import com.javafamily.bean.Pets;
import com.javafamily.repository.PetsRepository;
import com.javafamily.service.PetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PetsServiceImpl implements PetsService {

    @Autowired
    private PetsRepository repository;

    @Override
    public boolean savePets(Pets pets) {
        Pets obj = repository.save(pets);
        return obj != null ? true : false;
    }

    @Override
    public boolean removePetsById(Integer id) {
        if (repository.existsById(id)) {
            // 在数据库中指定的id若不存在，该方法会抛出异常
            repository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean modifyPets(Pets pets) {
        Pets obj = repository.save(pets);
        return obj != null ? true : false;
    }

    // 根据id查询
    @Override
    public Pets getPetsById(int id) {
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if (repository.existsById(id)) {
            // 在数据库中指定的id若不存在，该方法会抛出异常
            return repository.getOne(id);
        }
        Pets pets = new Pets();
        pets.setName("dog");
        return pets;
    }

    @Override
    public List<Pets> listAllPets() {
        return null;
    }

    @Override
    public List<Pets> findPetsByIdOrName(@RequestBody Pets pets) {
        return repository.findPetsByIdOrName(pets.getId(), pets.getName());
    }

}
